<?php

//    HookController PHP class.

//    Copyright (C) 2009 Henrik Nordquist.
//
//    This code is property of the CodeArray PHP project.  Rights Reserved!
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.

define("MODULE_DIR", "modules/");

class HookController
{
	/**
	 * Array of registered hooks.
	 *
	 * @var array
	 */
	protected $hooks = array();
	
	/**
	 * Register a hook for the system, which modules can attach to.
	 *
	 * @param string $hook
	 * @return bool
	 */
	public function registerHook($hook)
	{
		if(!is_string($hook))
		{
			return false;
		}
		
		$this->hooks[] = $hook;
		return true;
	}
	
	/**
	 * Redefines MODULE_DIR
	 *
	 * @param string $newdir
	 */
	public function setModuleDir($newdir)
	{
		if(is_dir($newdir))
			define("MODULE_DIR", $newdir);
	}
	
	/**
	 * Start the hooking!
	 * 
	 * Scanning the module directory, MODULE_DIR, reading the configuration,
	 * including files specified in the configuration, then runs the code
	 * for each matched hook.
	 *
	 * @return bool
	 */
	public function initHooks()
	{
		$entries = scandir(MODULE_DIR);
		
		foreach ($entries as $entry)
		{
			if(!is_dir(MODULE_DIR.$entry))
			{
				continue;
			}
			
			$module_root = MODULE_DIR.$entry."/";
			
			if(file_exists($module_root."mod.xml"))
			{
				$xml = simplexml_load_file($module_root."mod.xml");
				
				foreach ($xml->Includes->Source as $source)
				{
					if(file_exists($module_root.$source))
					{
						include_once($module_root.$source);
					}
				}
				
				foreach ($xml->Hooks->Hook as $hook)
				{
					if(in_array($hook['event'], $this->hooks))
					{
						eval($hook['action']);
					}
				}
			}
		}
		return true;
	}
	
	public function issetHook($hook)
	{
		if(in_array($hook, $this->hooks))
		{
			return true;
		}
		
		return false;
	}
}

?>